package com.jiaai.auth.util;



import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.jiaai.auth.model.AccessToken;
import com.jiaai.auth.model.AccessUser;
import com.jiaai.auth.model.UserEntity;
import com.jiaai.exception.TokenException;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * <p>
 *
 * </p>
 * @title  ${}
 * @author 佳爱网络科技
 * @version V1.0
 * @since 2017-7-10
 */
public class JWTEncryptUtil {
    private final  static  String  SECRET="JIAAI_SCERET_2017";

    //获取拉流的token
    public static String getPullToken(String mId) throws Exception {
        Date iat=new Date();
        Calendar eat = Calendar.getInstance();
        eat.setTime(iat);
        eat.add(Calendar.MINUTE, 1);// 1分钟
        JWTCreator.Builder  builder= JWT.create();
        builder.withIssuedAt(iat);
        builder.withIssuer("pull_url_jiaai");
        builder.withExpiresAt(eat.getTime());

        builder.withClaim("mId", mId);
        builder.withClaim("createTime", new Date().getTime());

        String token=builder.sign(Algorithm.HMAC256(SECRET));

        return token;
    }

    /**
     * 生成token
     * @param accessUser
     * @return
     * @throws Exception
     */
    public static AccessToken encrypt(AccessUser accessUser, String issuer, int day)throws Exception{
        AccessToken accessToken=new AccessToken();
        Date iat=new Date();
        Calendar eat = Calendar.getInstance();
        eat.setTime(iat);
        eat.add(Calendar.DAY_OF_MONTH, day);// 今天+1天
        JWTCreator.Builder  builder= JWT.create();
        builder.withIssuedAt(iat);
        builder.withIssuer(issuer);
        builder.withExpiresAt(eat.getTime());
        builder.withClaim("nickName",accessUser.getNickName());
        builder.withClaim("userId",accessUser.getUserId());
        builder.withClaim("isVisitor", accessUser.isVisitor());
        builder.withClaim("isVip", accessUser.isVip());
        String token=builder.sign(Algorithm.HMAC256(SECRET));
        //accessToken.setExpires_in(eat.getTime().getTime());

        accessToken.setAccess_token(token);
        return accessToken;
    }

    /**
     * 生成管理员token
     * @param issuer
     * @param day
     * @return
     * @throws Exception
     */
    public static String getUserToken(String issuer, int day, String nickName, String auth) throws Exception {
        Date iat=new Date();
        Calendar eat = Calendar.getInstance();
        eat.setTime(iat);
        eat.add(Calendar.DAY_OF_MONTH, day);// 今天+1天
        JWTCreator.Builder  builder= JWT.create();
        builder.withIssuedAt(iat);
        builder.withIssuer(issuer);
        builder.withExpiresAt(eat.getTime());
        builder.withClaim("role", "admin");
        builder.withClaim("nickName", nickName);
        builder.withClaim("auth", auth);
        String token=builder.sign(Algorithm.HMAC256(SECRET));

        return token;
    }

    /**
     * 解析管理员token
     * @param token
     * @return
     */
    public static UserEntity decryptUserToken(String token){
        try {
            JWTVerifier verifier = null;
            verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            DecodedJWT jwt = verifier.verify(token);
            Map<String, Claim> claims = jwt.getClaims();
            if (claims.get("role").asString().equals("admin")){
                return new UserEntity(claims.get("nickName").asString(), claims.get("auth").asString().split(","));
            }
            else return null;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * token解码
     * @param token
     * @return
     * @throws Exception
     */
    public  static AccessUser decrypt(String token)throws Exception{
        try {
            JWTVerifier verifier = null;
            verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            DecodedJWT jwt = verifier.verify(token);
            Map<String, Claim> claims = jwt.getClaims();
            AccessUser accessUser=new AccessUser();
            accessUser.setNickName(claims.get("nickName").asString());
            accessUser.setUserId(claims.get("userId").asString());
            accessUser.setVisitor(claims.get("isVisitor").asBoolean());
            accessUser.setVip(claims.get("isVip").asBoolean());
            return accessUser;
        }catch (Exception e){
            throw  new TokenException(e.getMessage());
        }
    }
}
